﻿function  uuid(len, radix) {
    var  chars =  '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz' .split( '' );
    var  uuid = [], i;
    radix = radix || chars.length;

    if  (len) {
        // Compact form
        for  (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random()*radix];
    }  else  {
        // rfc4122, version 4 form
        var  r;

        // rfc4122 requires these characters
        uuid[8] = uuid[13] = uuid[18] = uuid[23] =  '-' ;
        uuid[14] =  '4' ;

        // Fill in random data.  At i==19 set the high bits of clock sequence as
        // per rfc4122, sec. 4.1.5
        for  (i = 0; i < 36; i++) {
            if  (!uuid[i]) {
                r = 0 | Math.random()*16;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
    }

    return  uuid.join( '' );
}
$(function () {
    //Init();
    //日期选择
    $("#AllcheckId").click(function () {
        if ($('#AllcheckId').is(':checked')) {
            $("[name='checkId']").attr("checked", 'true');//全选 
        } else {
            $("[name='checkId']").removeAttr("checked");//取消全选 
        }

    })
    //初始化地区选择器
    var $citypicker1 = $('#sendFullAddress');
    var $citypicker2 = $('#ReceiveFullAddress');

    //将当前页面的标题banner高亮显示
    $(".navList ul li").eq(1).find("a").css("color", "#ed6900");

    //点击提交订单
    $("#orderSubmit").click(function () {
        //表单验证  寄件人信息验证
        if ($("input[name='senderName']").val() == undefined || $("input[name='senderName']").val() == "") {
            layer.msg("请填写寄件人姓名");
            $("input[name='senderName']").focus();
            return false;
        }
        if (!/(^[\u4E00-\u9FA5]+$)|(^[\u4E00-\u9FA5]*·[\u4E00-\u9FA5]*$)/.test($("input[name='senderName']").val())) {
            layer.msg("寄件人姓名格式不正确");
            $("input[name='senderName']").focus();
            return false;
        }
        if ($("input[name='senderMobile']").val() == "" && $("input[name='senderLandlineNumber']").val() == "") {
            layer.msg("手机号码和座机号码必须填写一个");
            $("input[name='senderMobile']").focus();
            return false;
        }
        if ($("input[name='senderMobile']").val() && $("input[name='senderMobile']").val().length > 11) {
            layer.msg("您输入的手机号码不正确");
            $("input[name='senderMobile']").focus();
            return false;
        }
        if ($("input[name='senderMobile']").val() && !$("input[name='senderMobile']").val().match(/^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\d{8})$/)) {
            layer.msg("请输入有效的手机号码");
            $("input[name='senderMobile']").focus();
            return false;
        }


        if ($("input[name='senderLandlineNumber']").val() &&
            (!$("input[name='senderLandlineNumber']").val().match(/^0[\d]{2,3}-[\d]{7,8}(-[\d]{4,4})?$/)) &&
            (!$("input[name='senderLandlineNumber']").val().match(/^400(\d{7}|-\d{4}-\d{3})$/))){
            layer.msg("寄件人座机号码输入错误");
            $("input[name='senderLandlineNumber']").focus();
            return false;
        }

        if ($("input[name='sendFullAddress']").val() == "") {
            layer.msg("请选择寄件人地址");
            $("input[name='sendFullAddress']").focus();
            return false;
        }

        if ($("input[name='sendFullAddress']").val().split("/").length != 3){
            layer.msg("请选择寄件人地址");
            $("input[name='sendFullAddress']").focus();
            return false;
        }

        if ($("input[name='sendAddress']").val() == "") {
            layer.msg("请填写寄件人详细地址");
            $("input[name='sendAddress']").focus();
            return false;
        }

        if($("input[name='senderEmail']").val() == "" || $("input[name='senderEmail']").val() == "undefined"){
            layer.msg("请填写邮箱");
            $("input[name='senderEmail']").focus();
            return false;
        }

        if(!$("input[name='senderEmail']").val().match(/^([\.a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/)){
            layer.msg("请输入有效的邮箱");
            $("input[name='senderEmail']").focus();
            return false;
        }

        if ($("select[name='paymentMethod']").val() == "请选择付款方式") {
            layer.msg("请选择付款方式");
            $("select[name='paymentMethod']").focus();
            return false;
        }

        if ($("#resultTbody > tr") && $("#resultTbody > tr").length <= 1) {
            layer.msg('导入收件人及物品信息!');
            return;
        }

        if ($("#resultTbody > tr") && $("#resultTbody > tr").length > 51) {
            layer.msg('抱歉，目前只支持单次最多50单!');
            return;
        }

        var objArr = [];
        var infoArr = [];

        $('#resultTbody tr').each(function (i) {// 遍历 tr
            infoArr=[]
            if (i == 0){
                return true
            }
            $(this).children('td').each(function (j) {  // 遍历 tr 的各个 td
                if (j == 0){
                    return true
                }
                // console.log("第" + (i + 1) + "行，第" + (j + 1) + "个td的值：" + $(this).text() + "。");
                infoArr.push($(this).text());
            });
            objArr.push(infoArr);
        });



        var myDate = new Date;
        var year = myDate.getFullYear(); //获取当前年
        var mon = myDate.getMonth() + 1; //获取当前月
        var date = myDate.getDate();
        var ms = myDate.getMilliseconds();

        function tojson(arr){
            if(!arr.length) return null;
            array = [];
            for(var i = 0;i < arr.length; i++){
                    array.push({
                        "homeUser":{id:$("input[name='homeUser.id']").val()},
                        "waybillNumber":year+""+mon+date+ms+""+uuid(7,[i]+3),
                        "senderName":$("input[name='senderName']").val().trim(),
                        "senderMobile":$("input[name='senderMobile']").val().trim(),
                        "senderLandlineNumber":$("input[name='senderLandlineNumber']").val().trim(),
                        "sendFullAddress":$("input[name='sendFullAddress']").val().trim(),
                        "sendAddress":$("input[name='sendAddress']").val().trim(),
                        "senderEmail":$("input[name='senderEmail']").val().trim(),
                        "paymentMethod":$("select[name='paymentMethod']").val().trim(),
                        "recipientsName":arr[i][0],
                        "recipientsMobile":arr[i][1],
                        "recipientsLandlineNumber":arr[i][2],
                        "recipientsFullAddress":arr[i][3]+"/"+arr[i][4]+"/"+arr[i][5],
                        "recipientsAddress":arr[i][6],
                        "itemType":arr[i][7],
                        "itemWeight":arr[i][8],
                        "remark":arr[i][9]
                    });
            }
            return JSON.stringify(array);
        }

        let recipientsInfo = tojson(objArr);

        // 记录阴影弹窗的索引，确保在必要时可以顺利获取到它，并对其关闭
        var shadeLayerIndex = 0;

        layer.open({
            content: '您确定下单吗？',
            btn: ['确定', '取消'],
            shadeClose: false,
            yes: function () {
                layer.msg("您已确认下单");
                // 发起请求
                $.ajax({
                    data: {
                        recipientsInfo:recipientsInfo,
                    },
                    url: '/home/expressMailOrder/saveAdd',
                    type: "POST",
                    dataType: "json",
                    success: function (result) {
                        if (result.code == 0) {
                            layer.close(shadeLayerIndex);
                            layer.open({
                                content:"您已成功下单!",
                                time: 1000,
                                end: function () {
                                    layer.msg("您已成功下单，感谢下单!稍后将跳转至首页");
                                    //下单成功跳转到首页页面
                                    setInterval(function () {
                                        window.location.href = "/home/entryPage/index";
                                    }, 1000)
                                }
                            });
                        } else {
                            layer.msg(result.msg);
                        }
                    },
                    error: function (result) {
                    },
                    beforeSend: function () {
                        // 提交表单时呈现阴影弹窗
                        shadeLayerIndex = layer.msg("订单提交中...");
                    },
                    complete: function () {
                        // 服务端返回响应信息时将关闭阴影弹窗
                        layer.close(shadeLayerIndex);
                    }
                });   // end ajax
            }, no: function () {
                layer.msg('您选择了取消');
            }
        });
    });

    //点击查询时效路由
    $("#priceSearch").click(function () {

        var senderProCityAres = $("#sendFullAddress").val()
        var acceptProCityArea = $("#ReceiveFullAddress").val()
        var articleweight = $("#Weight").val()
        if (senderProCityAres != "" && articleweight != "" && acceptProCityArea != "") {
            if (senderProCityAres.split('/').length - 1 == 2) {
                if (acceptProCityArea.split('/').length - 1 == 2) {
                    $.ajax({
                        url: "/Order/GetPriceMessage",
                        type: "Post",
                        data: {startCity: senderProCityAres, endCity: acceptProCityArea, weight: articleweight,},
                        success: function (result) {
                            if (result.Status == true) {
                                //把值赋给显示的文本框中
                                jQuery("#Time").val(result.Data.Time);
                                jQuery("#Price").val(result.Data.Price + "元");
                            } else {
                                layer.msg(result.StatusMessage);
                            }
                        }
                    })
                } else {
                    layer.msg("抱歉,您的收件地址还没有选择完毕");
                }
            } else {
                layer.msg("抱歉,您的发件地还没有选择完毕");
            }
        } else {
            layer.msg("抱歉,发件区县,收件区县和物品重量不能为空");
        }
    });
    InitAutoComplete();
});

//输入手机号码带出寄件人地址信息,初始化autocomplete,选中时并赋值给文本框
function InitAutoComplete() {
    $("#SenderMobile").autocomplete({
        source: "",
        minLength: 11,
        select: function (event, ui) {
            //此处因手机号是本身输入的，所以select本身就已经赋值了，在后台value给定输入的值就可以了
            //$("#SenderMobile").val(ui.item.label.split("-")[0]);
            $("#SenderName").val(ui.item.label.split("-")[1]);
            $("#sendFullAddress").val(ui.item.label.split("-")[2] + "/" + ui.item.label.split("-")[3] + "/" + ui.item.label.split("-")[4]);
            $("#SendFullAddressDetail").val(ui.item.label.split("-")[5]);
        }
    });
    //收件人地址信息
    $("#ReceiveMobile").autocomplete({
        source: "",
        minLength: 11,
        select: function (event, ui) {
            //$("#SenderMobile").val(ui.item.label.split("-")[0]);
            $("#ReceiveName").val(ui.item.label.split("-")[1]);
            $("#ReceiveFullAddress").val(ui.item.label.split("-")[2] + "/" + ui.item.label.split("-")[3] + "/" + ui.item.label.split("-")[4]);
            $("#ReceiveFullAddressDetail").val(ui.item.label.split("-")[5]);
        }
    });
}

function Show() {
    layer.open({
        title: '会员注册服务协议',
        type: 1,
        area: ['750px', '850px'],
        shadeClose: true, //点击遮罩关闭
        content: $("#agreement")
    })
}


function func() {
    //获取被选中的option标签  
    var vs = $('select  option:selected').val();
    if (vs == "月结") {
        $('#MonthCustomerDiv').css({display: 'block'});
    } else {
        $('#MonthCustomerDiv').css({display: 'none'});
    }

}




function pageBtn(list) {
    var sum = Math.ceil(list.length / 10);
    for (var i = 0, ahtml = ""; i < sum; i++) {
        if (i === 0) {
            ahtml += '<a class="cur" onclick="pageData(' + i + ');" href="javascript:;">' + (i + 1) + '</a>';
        } else {
            ahtml += '<a onclick="pageData(' + i + ');" href="javascript:;">' + (i + 1) + '</a>';
        }
    }
    $('.create_order_more_page_box').html(ahtml);
}

var savePageIndex = 0;

function pageData(index) {
    var obj = orders;
    if ($("#errorbtn").hasClass('cur'))
        obj = errorders;
    var data = obj.slice(index * 10, 10 * (index + 1));
    savePageIndex = index;
    $(".create_order_more_page_box a").removeClass('cur');
    $(".create_order_more_page_box a").eq(index).addClass('cur');
    $("#addressList").empty();
    $("#addressList").append($("#BatchOrderItemTemplet").tmpl(data));

}


function DelOrderData() {
    var No = 0;

    var boxes = $("input[name='checkId']");

    for (var i = 0; i < boxes.length; i++) {
        if (boxes[i].checked) {
            No++;
            $(boxes[i]).parents()[1].remove()
        }
    }
    if (No == 0) {
        layer.msg('请至少选择一条');
    }

}




